define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pt/grade/index' + location.search,
                    add_url: 'pt/grade/add',
                    edit_url: 'pt/grade/edit',
                    del_url: 'pt/grade/del',
                    multi_url: 'pt/grade/multi',
                    import_url: 'pt/grade/import',
                    table: 'pt_grade',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                sortOrder: 'asc',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'grade_code', title: __('Grade_code'), operate: 'LIKE'},
                        {field: 'grade_name', title: __('Grade_name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'work_details', title: "工作细项", operate: false, formatter: function (value, row, index) {
                            try {
                                // 兼容多种键名与类型：数组/JSON字符串
                                var source = (row && (row.work_details || row.workDetails)) ?? value;
                                if (!source) return '-';
                                var list = Array.isArray(source) ? source : (typeof source === 'string' ? JSON.parse(source) : []);
                                if (!Array.isArray(list) || list.length === 0) return '-';

                                // 简单转义
                                var escape = function (s) {
                                    return String(s || '').replace(/[&<>"]/g, function (c) {
                                        return {'&': '&amp;','<': '&lt;','>': '&gt;','"': '&quot;'}[c] || c;
                                    });
                                };

                                var htmlParts = [];
                                for (var i = 0; i < list.length; i++) {
                                    var item = list[i] || {};
                                    var seq_no = item.seq_no != null ? item.seq_no : '';
                                    var work_detail_name = item.work_detail_name != null ? item.work_detail_name : '';
                                    htmlParts.push("<span style='color:#884ffb'>" + escape(seq_no)+" ."+ escape(work_detail_name) + "</span> <br/>");
                                }
                                return htmlParts.join('');
                            } catch (e) {
                                return '-';
                            }
                        }},
                     
                        {field: 'create_time', title: __('Create_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'update_time', title: __('Update_time'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.buttons,
                         buttons: [
                             {
                                 name: 'edit',
                                 text: __('Edit'),
                                 title: __('Edit'),
                                 classname: 'btn btn-xs btn-success btn-dialog',
                                 icon: 'fa fa-pencil',
                                 url: 'pt/grade/edit',
                                 extend: ' data-area=\'["1200px", "800px"]\' data-shade=\'0.3\''
                             },
                             {
                                 name: 'del',
                                 text: __('Delete'),
                                 title: __('Delete'),
                                 classname: 'btn btn-xs btn-danger btn-ajax',
                                 icon: 'fa fa-trash',
                                 url: 'pt/grade/del',
                                 confirm: __('确定删除吗,删除后将清理职称下的所有工作细项?'),
                                 success: function(data, ret) {
                                     if (ret.code === 1) {
                                         $("a.btn-refresh").trigger("click");
                                     }
                                 }
                             }
                         ]}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            Controller.api.bindFieldlistEvents();
        },
        edit: function () {
            Controller.api.bindevent();
            Controller.api.bindFieldlistEvents();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            bindFieldlistEvents: function () {
                // 绑定fieldlist事件，自动重新排列序号
                $(document).on('click', '.btn-append', function () {
                    setTimeout(function () {
                        Controller.api.reorderSequence();
                    }, 100);
                });
                
                $(document).on('click', '.btn-remove', function () {
                    setTimeout(function () {
                        Controller.api.reorderSequence();
                    }, 100);
                });
                
                // 监听拖拽排序事件 - 使用多种事件确保捕获
                $(document).on('dragend', '.btn-dragsort', function () {
                    setTimeout(function () {
                        Controller.api.reorderSequence();
                    }, 100);
                });
                
                // 监听拖拽排序完成事件（FastAdmin的拖拽事件）
                $(document).on('dragsort.success', '.fieldlist', function () {
                    setTimeout(function () {
                        Controller.api.reorderSequence();
                    }, 100);
                });
                
                // 监听拖拽排序完成事件（jQuery UI sortable）
                $(document).on('sortupdate', '.fieldlist', function () {
                    setTimeout(function () {
                        Controller.api.reorderSequence();
                    }, 100);
                });
                
                // 监听拖拽排序完成事件（通用拖拽事件）
                $(document).on('drop', '.fieldlist', function () {
                    setTimeout(function () {
                        Controller.api.reorderSequence();
                    }, 100);
                });
                
                // 监听拖拽排序完成事件（FastAdmin fieldlist事件）
                $(document).on('fieldlist.sort', '.fieldlist', function () {
                    setTimeout(function () {
                        Controller.api.reorderSequence();
                    }, 100);
                });
                
                // 使用MutationObserver监听DOM变化
                var observer = new MutationObserver(function(mutations) {
                    mutations.forEach(function(mutation) {
                        if (mutation.type === 'childList') {
                            setTimeout(function () {
                                Controller.api.reorderSequence();
                            }, 100);
                        }
                    });
                });
                
                // 观察fieldlist的DOM变化
                var fieldlist = document.querySelector('.fieldlist');
                if (fieldlist) {
                    observer.observe(fieldlist, {
                        childList: true,
                        subtree: true
                    });
                }
                
                // 初始化时也重新排列一次
                setTimeout(function () {
                    Controller.api.reorderSequence();
                }, 200);
            },
            reorderSequence: function () {
                // 重新排列序号
                var rowIndex = 0;
                $('.fieldlist .form-inline').each(function (index) {
                    // 跳过表头和添加按钮行
                    if ($(this).hasClass('header-box-title') || $(this).find('.btn-append').length > 0) {
                        return;
                    }
                    
                    // 确保这是数据行（包含序号输入框）
                    var seqInput = $(this).find('input[name*="[seq_no]"]');
                    if (seqInput.length > 0) {
                        // 更新序号输入框的值（从1开始）
                        seqInput.val(rowIndex + 1);
                        rowIndex++;
                    }
                });
            }
        }
    };
    return Controller;
});
